import {
  Block,
  View,
  ScrollView,
  Swiper,
  SwiperItem,
  Text,
  Image,
  Button
} from '@tarojs/components'
import Taro from '@tarojs/taro'
import withWeapp from '@tarojs/with-weapp'
import { AtMessage } from 'taro-ui'
import Article from '../../component/article'
import Page from '../../component/page';
import './index.scss'


const flow = require('../../utils/flow.js')
const modules = require('./module.js')
const { getUserInfo, transSuccToPro, onShow } = require('../../utils/util.js')
const regeneratorRuntime = require('../../utils/async.js')

const app = Taro.getApp()

@withWeapp('Page')
class _C extends Taro.Component {
  state = {
    userInfo: {},
    hasUserInfo: false,
    canIUse: Taro.canIUse('button.open-type.getUserInfo'),
    articles: {}, // 每页view的文章 [ { articles: [], pageIndex: 1, total: 100, hasMore: false } ]
    myTags: [], // 用户订阅的tag
    subs: [],
    showTagPanel: false,
    tags: [],
    tagCls: {},
    tagSaveTips: '',
    tagSaveCls: 'tag-save unselected',
    shadowCls: 'shadow',
    selectedTag: '我的', // 当前选中的tag
    toView: 'toView0', // 当前选中tag对应的panel
    scrollLeft: '200rpx',
    headerViewItem: '', // 当前选中tag对应的header-item
    statusBarHeight: app.globalData.statusBarHeight,
    swiperHeight: app.globalData.contentHeight + 33,
    swiperTopHeight: app.globalData.headerHeight + 33,
    defaultTagName: '我的'
  }
  onLoadMore = async e => {
    // const { name } = e.target.dataset
    const { defaultTagName, articles } = this.state;
    const curTag = articles[defaultTagName];

    if (curTag.hasMore) {
      await this.flow.dispatch('loadMore', {
        key: defaultTagName,
        pageIndex: curTag.pageIndex + 1
      })
    }
  }
  initPage = async () => {
    const loginRes = await transSuccToPro(wx.login.bind(wx))
    // 发送 res.code 到后台换取 openId, sessionKey, unionId
    await this.flow.dispatch('wxlogin', {
      appname: 'avote',
      code: loginRes.code
    })

    const num = await this.fetchList();
    await this.flow.dispatch('getMeAndTags');
    // await this.flow.dispatch('getTags');

    if (num) {
      Taro.showToast({
        title: num ? `已更新${num}篇内容` : '暂无更新',
        icon: 'none'
      });
    }
  }
  componentWillMount = async () => {
    this.flow = new flow(
      this,
      modules
    )
    this.initPage();
  }
  async fetchList() {
    await this.flow.dispatch('getList', { key: '我的' });
    const { articles, defaultTagName } = this.state;
    const current = articles[defaultTagName]
    return current && current.updateNum;
  }
  onPullDownRefresh = async () => {
    console.log('onPullDownRefresh', '下拉刷新....');
    const num = await this.fetchList();
    console.log('num:' + num);
    Taro.stopPullDownRefresh();//停止下拉动作过渡
    Taro.showToast({
      title: num ? `已更新${num}篇内容` : '暂无更新',
      icon: 'none'
    });
    if (num) {
      this.setState({ scrollTop: Math.random() })
    }
  }
  onRefresh = () => {
    Taro.startPullDownRefresh()//停止下拉动作过渡
  }
  setTag = e => {
    const { tags, tagCls, subs } = this.data
    const name = e.currentTarget.dataset.name

    if (tagCls[name]) {
      tags.splice(tags.findIndex(tag => tag === name), 1)
      delete tagCls[name]
    } else {
      tags.push(name)
      tagCls[name] = 'tag-item tag-item-selected'
    }

    this.setState({
      tags,
      tagCls,
      tagSaveTips: `${tags.length}/${subs.length}`,
      tagSaveCls: tags.length ? 'tag-save' : 'tag-save unselected'
    })
  }
  saveTags = () => {
    const { tags } = this.data

    if (tags.length) {
      this.flow.dispatch('saveTags', { tags })
    }
  }
  onTagChange = async e => {
    const { myTags } = this.data
    const tag = e.currentTarget.dataset.name
    const param =
      tag === '我的'
        ? {}
        : {
            tag
            // const list = await this.flow.dispatch('getList', param);
          }
    this.setState({
      toView: `toView${myTags.findIndex(t => t === tag)}`,
      selectedTag: tag
    })
  }
  catchtouchend = () => {
    const { viewIndex } = this
    const { myTags } = this.data

    this.setState({
      toView: `toView${viewIndex}`,
      selectedTag: myTags[viewIndex]
    })
  }
  onScroll = e => {
    const { myTags } = this.data
    const { current } = e.detail

    this.setState({
      toView: `toView${current}`,
      selectedTag: myTags[current],
      headerViewItem: `item${current}`
    })
  }
  componentDidShow = onShow
  config = {
    navigationBarTitleText: '',
    enablePullDownRefresh: true,
  }

  render() {
    const { headerHeight, contentHeight } = app.globalData
    const {
      articles,
      showTagPanel,
      tagSaveTips,
      tagCls,
      subs, 
      tagSaveCls,
      scrollTop,
      defaultTagName
    } = this.state

    const current = articles[defaultTagName]

    return (
      <View>
        <View className="refreash-container" onTap={this.onRefresh}> 
          <Text className="fa fa-refresh fa-lg" />
        </View>
        <AtMessage />
        <Page title="安问阅读" />
        <ScrollView
          className="page-container"
          scrollWithAnimation="true"
          currentItemId={toView} 
          onScrollToLower={this.onLoadMore}
          scrollTop={scrollTop}
          scrollY="true"
          style={`height: ${contentHeight - 10}px;margin-top: ${headerHeight + 5}px`}
        >
          <View className="page" scrollY="true" >
            <View className="article-container">
              {
                current && current.articles && current.articles.map((article, index) => {
                  return <Article article={article} />
                })
              }
              <View
                className={
                  current.showLoading ? 'more-arts' : 'hide'
                }
              >
                加载中...
              </View>
              <View
                className={
                  current.hasMore ? 'hide' : 'no-more-arts'
                }
              >
                --没有更多内容了--
              </View>
            </View>
          </View>
        </ScrollView>
        <View className={showTagPanel ? 'shadow' : 'hide'} />
        <View className={showTagPanel ? 'tag-panel' : 'hide'}>
          <View className="tag-setting">
            <View className="tag-title">
              {'请选择感兴趣的标签' +
                (tagSaveTips ? '(' + tagSaveTips + ')' : '')}
            </View>
            <View className="tag-panel-container">
              {subs.map((item, index) => {
                return (
                  <View
                    className={
                      (tagCls[item.name] || 'tag-item') +
                      ' ' +
                      (item.pos ? 'hidden' : '')
                    }
                    onClick={this.setTag}
                    data-name={item.name}
                    key={index}
                  >
                    {item.name}
                  </View>
                )
              })}
            </View> 
            <Button onClick={this.saveTags} className={tagSaveCls}>
              保存
            </Button>
          </View>
        </View>
      </View>
    )
  }
}

export default _C
